<template>
  <el-dialog v-model="dialogVisible" title="请完成下列验证后继续" :width="width" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <SliderCaptcha ref="sliderCaptchaRef" :phone="phone" @verify-success="handleVerifySuccess"
      @verify-fail="handleVerifyFail" />
  </el-dialog>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue';
import SliderCaptcha from './common/slider-captcha.vue';

// 组件参数
const props = defineProps({
  width: {
    type: String,
    default: '300px'
  },
  visible: {
    type: Boolean,
    default: false,
    required: true
  },
  phone: {
    type: String,
    default: '',
    required: true
  }
});
let time = null;
// 组件事件
const emit = defineEmits(['update:visible', 'verify-success', 'verify-fail', 'cancel']);

// 状态变量
const dialogVisible = ref(false);
const sliderCaptchaRef = ref(null);
const isVerifying = ref(false);

// 监听 visible 属性变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal;
  if (newVal) {
    nextTick(() => {
      sliderCaptchaRef.value.refresh();
      // 动态设置样式覆盖
      removeHeaderBorder();
    });
  } else {
    sliderCaptchaRef.value.reset();
    time && clearTimeout(time);
  }
});

// 动态移除头部边框
const removeHeaderBorder = () => {
  nextTick(() => {
    // 查找弹窗中的 header 元素
    const headers = document.querySelectorAll('.el-dialog header, .el-dialog .el-dialog__header');
    headers.forEach(header => {
      header.style.setProperty('border-bottom', '0', 'important');
    });
  });
};

// 监听弹窗显示状态变化
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal);
});

// 处理验证成功
const handleVerifySuccess = (data) => {
  isVerifying.value = false;
  
  time = setTimeout(() => {
    dialogVisible.value = false;
    emit('verify-success', data);
  }, 1500);
};

// 处理验证失败
const handleVerifyFail = () => {
  isVerifying.value = false;
  emit('verify-fail');
};

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false;
  emit('cancel');
};

// 处理刷新验证码
const handleRefresh = () => {
  if (sliderCaptchaRef.value) {
    sliderCaptchaRef.value.refresh();
  }
};

// 暴露方法给父组件
defineExpose({
  refresh: () => {
    if (sliderCaptchaRef.value) {
      sliderCaptchaRef.value.refresh();
    }
  },
  open: () => {
    dialogVisible.value = true;
  },
  close: () => {
    dialogVisible.value = false;
  }
});
</script>

<style scoped>
:deep(.el-dialog .el-dialog__body) {
  padding: 0 !important;
}
</style>
